import {promiseGetStorage, promiseLogin, promiseRequest, promiseSetStorage} from "./index";

const api = {
  login: async (code) => {
    const result = await promiseRequest(`/auth/wechat`, 'POST', {
      data: {
        code: code
      }
    })
    return result["data"];
  },
  async refreshToken() {
    const code = await promiseLogin();
    const token = await this.login(code);
    await promiseSetStorage("token", token);
    return token;
  },
  checkLogin: async (token) => {
    try {
      await promiseRequest("/checkLogin", "GET", {
        toast: false, header: {
          Authorization: `Bearer ${token}`
        }
      })
    } catch (e) {
      return false;
    }
    return true;
  },
  async updateLoginStatus() {
    let token = await promiseGetStorage("token");
    if (token && await this.checkLogin(token)) {
      return token;
    }
    return await this.refreshToken();
  }
}
export default api;
